#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gettext

class I18n:
	"""
	Provides user authentication and session management
	"""

	def __init__(self, app, **args):
		"""
		app - WSGI application to execute 
		Exports gettext function to 
		"""
		self.app = app

	def __call__(self, environ, start_response):
 		cf = environ['renyare.config']
		lang = environ['renyare.config'].get('renyare', 'language')
		langs = environ['renyare.config'].get('renyare', 'languages')
		if 'HTTP_ACCEPT_LANGUAGE' in environ:
			langs = langs.split(',')
			ht_langs = environ['HTTP_ACCEPT_LANGUAGE'].split(',')
			for l in ht_langs:
				ll = l.split('-')[0]
				if ll in langs:
					lang = l
					break
		environ['renyare.language'] = lang
		try:
			lang = gettext.translation('renyare', [lang])
			lang.install(unicode=True)
		except:
			def nogettext(text): 
				return text
			if glob:
				import __builtin__
				__builtin__.__dict__['_'] = nogettext
		return self.app(environ, start_response)

